#include "acctauthenticate.h"
#include <QDebug>
AcctAuthenticate::AcctAuthenticate(QObject *parent)
    : QObject{parent}
{

}

AcctAuthenticate::~AcctAuthenticate()
{
#ifndef _WIN32
    if (mPamHandle)
        pam_end(mPamHandle, PAM_SUCCESS);
    mPamHandle = 0;
#endif
}

#ifndef _WIN32
bool AcctAuthenticate::pam_module_init(const char* username)
{
    mConv.appdata_ptr = (void *)(this);
    mConv.conv = &pam_conv_callback;
    const int res = pam_start("login", username, &mConv, &mPamHandle);
    if (res != PAM_SUCCESS)
    {
        throw std::runtime_error("Failed to initialize PAM");
        return false;
    }
    return true;
}

void AcctAuthenticate::pam_module_finit()
{
    if (mPamHandle)
        pam_end(mPamHandle, PAM_SUCCESS);
    mPamHandle = 0;
}

bool AcctAuthenticate::pam_module_auth(const char* passwd)
{
    mPassword = passwd;
    const int res = pam_authenticate(mPamHandle, 0);
    if (res != PAM_SUCCESS)
        qDebug() << "pam_authenticate " << res;
    return res == PAM_SUCCESS;
}

int AcctAuthenticate::pam_conv_callback (int msgId, const pam_message **msg, pam_response **resp, void *appData)
{
    Q_UNUSED(msgId)
    Q_UNUSED(msg)
    AcctAuthenticate *me = static_cast<AcctAuthenticate *>(appData);
    pam_response *reply = static_cast<pam_response *>(calloc(1, sizeof(pam_response)));
    reply->resp = strdup(me->mPassword);
    reply->resp_retcode = 0;
    *resp = reply;
    return PAM_SUCCESS;
}
#endif
